package cn.jiyun.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义过滤器
 */
@Component
public class MyAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求参数中带有token 内容，就放行，否则提示未授权
        //获取请求和响应对象对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求参数  name=zhangsan&token=123
        MultiValueMap<String, String> map = request.getQueryParams();
        List<String> list = map.get("token");
        //判断token是否传递
        if(CollectionUtils.isEmpty(list)){
            //没有传递token，说明权限不足，拦截请求
            //设置权限不足的状态码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        //放行请求
        return chain.filter(exchange);
    }

    //过滤器执行顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
